<template>
  <view id="appointmentConfirm" class="page">
    <view class="bg_group_view">
      <view class="bg_item_view">
        <text class="red_star">*</text>
        <text class="form_title_text">服务门店</text>
        <text class="form_content_text">建业车便利(建业城市花园店)</text>
      </view>

      <view class="bg_item_view">
        <text class="red_star">*</text>
        <text class="form_title_text">预约时间</text>
        <view @tap="selectAppointTime">
          <text class="form_content_text">></text>
          <text class="form_content_arrow_text" v-if="isShowAppointTime"
            >{{ shortReservationDate }} {{ startTime }}-{{ endTime }}</text
          >
          <text class="form_content_arrow_text" v-else>请选择到店服务时间</text>
        </view>
      </view>

      <view class="bg_item_view">
        <text class="form_title_text">预约人手机号</text>
        <text class="form_content_text">{{ formData.mobile }}</text>
      </view>

      <view class="bg_item_view_plate">
        <text class="red_star_plate">*</text>
        <text class="form_title_text_plate">预约车辆</text>
        <view class="key_board_view" id="keysPosition">
          <key-board
            class="key-board"
            :carNum="carNum"
            :resetPlate="resetPlate"
            @onOk="onOk"
            @keyBoardShow="keyBoardShow"
            bind:onCancel="onCancel"
            id="keyBoard"
          />
        </view>
      </view>
    </view>

    <view class="bg_group_view_1">
      <view class="appoint_server_small_view"
        ><image
          src="../../../image/icon_appointment.png"
          class="appoint_server_small_img"
        ></image>
        <view class="appoint_server_title_view"> 预约服务 </view></view
      >

      <view class="appoint_server_big_view"
        ><image
          :src="`${imageBaseUrl}/${serviceImageUrl}`"
          class="appoint_server_big_img"
        ></image>
        <text class="appoint_server_name_text">{{ serviceName }}</text></view
      >

      <text class="appoint_server_tip_text"
        >温馨提示：具体价格以门店为准（不同品牌和车型费用会不同）</text
      >
    </view>
    <view class="bg_group_view_1">
      <view class="appoint_process_title_view">
        <text class="appoint_process_title">－ 预约流程 －</text>
      </view>
      <view class="appoint_process_outer_bg">
        <image
          class="circle_image"
          src="../../../image/appoint_online.png"
        ></image>
        <image
          class="appoint_process_arrow_image"
          src="../../../image/green_arrow.png"
        ></image>
        <image
          class="circle_image"
          src="../../../image/server_at_shop.png"
        ></image>
        <image
          class="appoint_process_arrow_image"
          src="../../../image/green_arrow.png"
        ></image>
        <image class="circle_image" src="../../../image/pay_circle.png"></image>
      </view>

      <view class="appoint_process_bottom_bg">
        <text class="appoint_process_bottom_pub_text">在线预约</text>
        <text
          class="
            appoint_process_bottom_pub_text appoint_process_bottom_last_text
          "
          >到店服务</text
        >
        <text
          class="
            appoint_process_bottom_pub_text appoint_process_bottom_last_text
          "
          >结算交付</text
        >
      </view>
    </view>
    <view class="bg_group_view_2">
      <view class="bg_item_view">
        <text class="desc_title_text">预约备注</text>
        <view class="input_view">
          <input
            type="text"
            placeholder="请输入备注"
            class="input_desc"
            placeholderStyle="color:#999999;"
            v-model="formData.remark"
            maxlength="50"
          />
        </view>
      </view>
    </view>

    <view class="bg_group_view_submit">
      <text class="submit_tip_text"
        >如需预约多个项目，可分次预约也可到店后直接告知接待人员</text
      >
      <view class="appoint_view" @tap="submitAppoint"> 立即预约 </view>
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./appointmentConfirm.less";
import keyBoard from "../../../components/keyBoard/keyBoard.vue";
import bulterApi from "@souche2014/bulter-api";
import { checkPlateNo,isFastClick } from "../../../check.js";
const api = bulterApi({ partner: "IOParking" });
const API_CarCode = process.env.IOParking.API_CARCODE;
const openIdMock = "oRPxj5bi2JB-id96cJ_s1wBWmjAo";
const mobileMock = "18039670989";
export default {
  name: "appointmentConfirm",
  data() {
    return {
      checkPlateNo,
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头部
      isShowAppointTime: false, //是否显示预约时间
      resetPlate: [],
      plate: "", //车牌号
      imageBaseUrl: process.env.IOParking.IMAGE_BASE,
      serviceName: "", //服务名称
      communityName: "", //项目名称
      serviceImageUrl: "", //服务图片
      formData: {},
      startTime: "",
      endTime: "",
      shortReservationDate: "",
    };
  },
  //mixins:[authorize],
  components: { keyBoard },
  mounted() {
    this.initForm();
  },
  onLoad: function (options) {
    console.log("参数:", JSON.stringify(options));
    if (options) {
      this.serviceName = options.serviceName;
      this.communityName = options.communityName;
      this.serviceImageUrl = options.serviceImageUrl;
      this.formData.communityId = options.communityId;
      this.formData.serviceId = options.serviceId;
    }
    try {
      var openId = Taro.getStorageSync("openId");
      var mobile = Taro.getStorageSync("mobile");
      if (!openId) {
        this.wx_login();
      } else {
        this.formData.mobile = mobile;
        this.formData.openId = openId;
        this.getLastPlateno(openId);
      }
      let nickName = Taro.getStorageSync("nickName");
      console.log("获取昵称：", nickName);
      this.formData.nickName = nickName;
      this.formData.headImgUrl = Taro.getStorageSync("avatarUrl");
    } catch (error) {
      this.wx_login();
    }
  },
  created() {},
  methods: {
    initForm() {
      this.formData = {
        communityId: 0,
        serviceId: 0,
        reservationDate: "",
        timeSlotId: 0,
        openId: "",
        nickName: "",
        headImgUrl: "",
        mobile: "",
        plateNo: "",
        remark: "",
      };
    },
    wx_login() {
      api
        .getUserInfo({
          scope: "all",
        })
        .then((resp) => {
          if (resp.success) {
            if (resp.data == "mock") {
              this.formData.mobile = mobileMock;
              this.formData.openId = openIdMock;
              this.getLastPlateno(openIdMock);
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      Taro.request({
        url: this.apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          if (res.data.isSuccess) {
            console.log("getInfos:", res.data);
            this.formData.mobile = res.data.data.phoneNum;
            this.formData.openId = res.data.data.openId;
            var userOpenId = res.data.data.openId;
            let mobileRes = res.data.data.phoneNum;
            if (userOpenId) {
              Taro.setStorage({
                key: "openId",
                data: userOpenId,
              });
            }
            if (mobileRes) {
              Taro.setStorage({
                key: "mobile",
                data: mobileRes,
              });
            }
            this.getLastPlateno(this.formData.openId);
          } else {
            console.log("getInfos失败");
          }
        },
      });
    },

    plateReset(e) {
      this.resetPlate = e.split("");
      this.formData.plateNo = e;
    },

    keyBoardShow(e) {
      if (e) {
        console.log(document.getElementById("keysPosition"));
        document.getElementById("keysPosition").style.paddingBottom = "0px";
        Taro.createSelectorQuery()
          .select("#keysPosition")
          .boundingClientRect(function (rect) {
            // 使页面滚动到底部
            Taro.pageScrollTo({
              scrollTop: rect.bottom,
            });
          })
          .exec();
      } else {
        document.getElementById("keysPosition").style.paddingBottom = "0px";
      }
    },

    //车牌号查询
    onOk(e) {
      this.formData.plateNo = e;
    },
    //立即预约
    submitAppoint() {
      console.log("点击预约，", this.formData);
      let reservationDate = this.shortReservationDate;
      if (!reservationDate) {
        Taro.showToast({
          title: "请选择预约时间",
          icon: "error",
          duration: 2000,
        });
      } else if (!this.formData.plateNo) {
        Taro.showToast({
          title: "请输入车牌号",
          icon: "error",
          duration: 2000,
        });
      } else if (!checkPlateNo(this.formData.plateNo.substr(1))) {
        Taro.showToast({
          title: "车牌号不正确",
          icon: "error",
          duration: 1000,
          mask: true,
        });
        return;
      } else {
        Taro.showLoading({
          title: "加载中",
          mask: true,
        });
        Taro.request({
          url: API_CarCode + "reservationorder/create",
          header: {
            "content-type": "application/json", // 默认值
          },
          data: this.formData,
          method: "POST",
          success: (res) => {
            console.log("提交：", res);
            Taro.hideLoading();
            if (res.data.isSuccess) {
              if (res.data.data) {
                let orderId = res.data.data.id;
                let time = `${this.startTime}-${this.endTime}`;
                let successUrl = `../appointmentSuccess/appointmentSuccess?orderId=${orderId}&date=${reservationDate}&time=${time}`;
                console.log("跳转路径：", successUrl);
                Taro.redirectTo({
                  url: successUrl,
                });
              }
            } else {
              Taro.showToast({
                title: res.data.message,
                icon: "warn",
                duration: 2000,
              });
            }
          },
        });
      }
    },

    //选择预约时间
    selectAppointTime() {
      if (isFastClick()) {
        return;
      }
      Taro.navigateTo({
        url: `../appointmentTime/appointmentTime?communityId=${this.formData.communityId}&ServiceId=${this.formData.serviceId}&currentDate=${this.formData.reservationDate}&currentSlotId=${this.formData.timeSlotId}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          acceptDataFromTimePage: (data) => {
            console.log("页面返回：", data);
            if (data) {
              if (data.reservationDate) {
                console.log("页面返回reservationDate不为空");
                this.isShowAppointTime = true;
                this.formData.reservationDate = data.reservationDate;
                this.shortReservationDate = data.reservationDate.substring(
                  0,
                  10
                );
                this.formData.timeSlotId = data.timeSlotId;
                this.startTime = data.startTime;
                this.endTime = data.endTime;
              } else {
                this.isShowAppointTime = false;
                console.log("页面返回reservationDate为空");
              }
            }
          },
        },
      });
    },

    //获取上次预约的车牌号
    getLastPlateno(myOpenId) {
      Taro.showLoading({
        title: "加载中",
        mask: true,
      });
      Taro.request({
        url: API_CarCode + `reservationorder/getplateno?id=${myOpenId}`,
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          Taro.hideLoading();
          if (res.data.isSuccess) {
            this.formData.plateNo = res.data.data;
            this.resetPlate = this.formData.plateNo.split("");
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "warn",
              duration: 2000,
            });
          }
        },
      });
    },    
    //end
  },
};
</script>

